package com.example.a12.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a12.R;
import com.example.a12.model.Novel;

import java.util.List;

public class NovelAdapter extends ArrayAdapter<Novel> {

    private int resourceId;

    public NovelAdapter(@NonNull Context context, int resource, @NonNull List<Novel> objects) {
        super(context, resource, objects);
        this.resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Novel novel = getItem(position);
        ViewHolder viewHolder;
        View view;

        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.novelImage = view.findViewById(R.id.novel_image);
            viewHolder.novelTitle = view.findViewById(R.id.novel_title);
            viewHolder.novelSummary = view.findViewById(R.id.novel_summary);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        if (novel != null) {
            // 确保方法名与Novel类中的方法一致
            viewHolder.novelImage.setImageResource(novel.getImageResourceId());
            viewHolder.novelTitle.setText(novel.getTitle());
            viewHolder.novelSummary.setText(novel.getSummary());
        }

        return view;
    }

    static class ViewHolder {
        ImageView novelImage;
        TextView novelTitle;
        TextView novelSummary;
    }
}